<?php

namespace App\Http\Middleware;

use Closure;
use App\Helpers\Code;
use App\Models\Account\User;
use App\Models\Account\UserCache;
use App\Models\Account\UserGroupMapUser;
use \Illuminate\Support\Facades\Response;

class CheckAcl
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if ($this->_getUserCache($request)) {
            $result = [
                'code' => Code::SYSTEM_NO_ACCESS,
                'data' => [],
                'msg' => '暂无权限'
            ];

            return Response::json($result);
        }

        return $next($request);
    }

    private function _getUserCache($request)
    {
        /*屏蔽中间件,待基础数据完善之后再删掉*/
        return false;

        /*管理员组所有权限均开放*/
        $uid = $request->user()->id;
        $adminGroup = UserGroupMapUser::where(['group_id' => Code::SUPER_ADMIN_GROUP_ID, 'user_id' => $uid])->first();
        if($adminGroup){
            return false;
        }

        /*不需要验证的路由*/
        $unVerifyApiArr = Code::ROUTE_ESCAPE;
        $routeName = $request->route()->getName();
        if(in_array($routeName,$unVerifyApiArr)){
            return false;
        }

        $userCache = UserCache::where(['user_id'=>$uid,'type'=>1])->first(['cache','expired_at']);
        $user = new User();
        if($userCache){
            $now = now();
            if($now > $userCache->expired_at){
                $user->getUserMenuList($uid);
                $userCache = UserCache::where(['user_id'=>$uid,'type'=>1])->first(['cache','expired_at']);
            }
        }else{
            $user->getUserMenuList($uid);
            $userCache = UserCache::where(['user_id'=>$uid,'type'=>1])->first(['cache','expired_at']);
        }

        $cacheArr = json_decode($userCache->cache,true);
        $apiArr = $cacheArr['apis'];
        if(in_array($routeName,$apiArr)){
            return false;
        }

        return true;
    }

}
